package com.cn.mmd.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;

/**
 * Created by Administrator on 2016/9/5 0005.
 */
public class AliyunOssUtil {
    static Log log = LogFactory.getLog(AliyunOssUtil.class);

    public synchronized static String save(String key, String filePath) {
        try {    // 使用默认的OSS服务器地址创建OSSClient对象
            AliyunOssConfig.load();
            OSSClient client = new OSSClient(AliyunOssConfig.OSS_ENDPOINT, AliyunOssConfig.ACCESS_ID, AliyunOssConfig.ACCESS_KEY);
//            ensureBucket(client, AliyunOssConfig.bucketName);
//            setBucketPublicReadable(client, AliyunOssConfig.bucketName);
            System.out.println("正在上传...");
            //      fileName = System.currentTimeMillis() + "." +getExtensionName(fileName);
            uploadFile(client, AliyunOssConfig.bucketName, key, filePath);
            // 设置URL过期时间为10年  3600l* 1000*24*365*10
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            // 生成URL
            URL url = client.generatePresignedUrl(AliyunOssConfig.bucketName, key,expiration);
            if (url != null) {
                System.out.println("成功");
                return url.toString();
            }
        } catch (Exception e) {
            log.error("上传失败");
        }
        return null;
    }
    // 如果Bucket不存在，则创建它。
//    private static void ensureBucket(OSSClient client, String bucketName) throws OSSException, ClientException {
//        if (client.isBucketExist(bucketName)) {
//            log.error("isBucketExist true");
//            return;
//        }
//         //创建bucket
//        client.createBucket(bucketName);
//    }

    // 删除一个Bucket和其中的Objects
    private static void deleteBucket(OSSClient client
            , String bucketName
    ) throws
            OSSException, ClientException {
        ObjectListing ObjectListing = client.listObjects(bucketName);
        List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();
        for (int i = 0; i < listDeletes.size(); i++) {
            String objectName = listDeletes.get(i).getKey();
            // 如果不为空，先删除bucket下的文件
            client.deleteObject(bucketName, objectName);
        }
        client.deleteBucket(bucketName);
    }

    // 把Bucket设置为所有人可读
    private static void setBucketPublicReadable(OSSClient client, String bucketName) throws OSSException, ClientException {
        //创建bucket
        client.createBucket(bucketName);
        //设置bucket的访问权限，public-read-write权限
        client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
    }

    // 上传文件
    private static void uploadFile(OSSClient client, String bucketName, String Objectkey, String filePath) throws OSSException, ClientException, FileNotFoundException {
        File file = new File(filePath);
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(file.length());
        // 可以在metadata中标记文件类型
        if (filePath.endsWith("xml")) {
            objectMeta.setContentType("text/xml");
        } else if (filePath.endsWith("jpg")) {
            objectMeta.setContentType("image/jpeg");
        } else if (filePath.endsWith("png")) {
            objectMeta.setContentType("image/png");
        }
        InputStream input = new FileInputStream(file);
        client.putObject(bucketName, Objectkey, input,
                objectMeta);
    }

    // 下载文件
    private static void downloadFile(OSSClient client, String bucketName, String key, String filename
    ) throws
            OSSException, ClientException {
        client.getObject(new GetObjectRequest(bucketName, key), new File(filename));
    }

}

